import cache from '@/plugins/cache'

const state = {
  /* 侧边栏状态 */
  sidebar:
  {
    isOpen: cache.local.get('sidebarIsOpen') ? !!+cache.local.get('sidebarIsOpen') : false,
    clickedMenuId: cache.local.get('sidebarclickedMenuId') || null
  },
  /* 子菜单 */
  subMenu:
  {
    list: cache.local.get('subMenuList') || [],
    clickedMenuId: cache.local.get('clickedSubMenuId') || '123456a',
  },
  /* 标签页 */
  tags:
  {
    list: cache.local.getJSON('tagsList') ? cache.local.getJSON('tagsList') : [],
    clickedTagsId: cache.local.get('clickedTagsId') || null,
    beforeClickedTagsId: cache.local.get('beforeClickedTagsId') || null,
  }
}

const mutations = {

  /* 切换侧边栏 */
  TOGGLE_SIDEBAR: state => {
    state.sidebar.isOpen = !state.sidebar.isOpen
    if (state.sidebar.isOpen) {
      cache.local.set('sidebarIsOpen', 1)
    }
    else {
      cache.local.set('sidebarIsOpen', 0)
    }
  },

  /* 点击左侧主菜单 */
  CHANGE_CLICKED_MENU_ID: (state, id) => {
    state.sidebar.clickedMenuId = id
    cache.local.set('sidebarclickedMenuId', id)
  },

  /* 点击左侧子菜单 */
  CHANGE_CLICKED_SUN_MENU_ID: (state, id) => {
    state.subMenu.clickedMenuId = id
    cache.local.set('clickedSubMenuId', id)
  },

  /* 设置子菜单的list */
  CHANGE_SUB_MENU_LIST: (state, list) => {
    state.subMenu.list = list
    cache.local.setJSON('subMenuList', list)
  },

  /* 设置tags的列表 */
  ADD_TAGS: (state, menuInfo) => {
    state.tags.beforeClickedTagsId = state.tags.clickedTagsId,
      cache.local.set('beforeClickedTagsId', state.tags.clickedTagsId)

    state.tags.clickedTagsId = menuInfo.childrenId,
      cache.local.set('clickedTagsId', menuInfo.childrenId)

    let tagList = cache.local.getJSON('tagsList') ? cache.local.getJSON('tagsList') : []
    for (let item of menuInfo.subList) {
      if (item.id === menuInfo.childrenId && (tagList.length === 0 || JSON.stringify(tagList).indexOf(JSON.stringify(item)) === -1)) {
        tagList.push(item);
        state.tags.list = tagList
        cache.local.setJSON('tagsList', tagList)
        break
      }
    }

  }
}

const actions = {
  /* 切换侧边栏 */
  toggleSideBar({ commit }) {
    commit('TOGGLE_SIDEBAR')
  },

  /* 路由改变时 */
  routerChange({ commit }, menuInfo) {
    commit('CHANGE_CLICKED_MENU_ID', menuInfo.parentId)
    commit('CHANGE_CLICKED_SUN_MENU_ID', menuInfo.childrenId)
    commit('CHANGE_SUB_MENU_LIST', menuInfo.subList)
    commit('ADD_TAGS', menuInfo)
  }
}

export default
  {
    namespaced: true,
    state,
    mutations,
    actions
  }